package cn.net.wanji.job;

import cn.net.wanji.entity.EventCar;
import cn.net.wanji.entity.VehicleRsuInfo;
import cn.net.wanji.mapper.MonitorMapper;
import cn.net.wanji.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

import static cn.net.wanji.service.iml.DataReceiveServiceImpl.carLicense;
import static cn.net.wanji.utils.TimeUtils.calculateMinutesDifference;


@Slf4j(topic = "定时处理事件列表【ServiceConfigJob】")
//@EnableScheduling
//@Component
public class RefreshCongestionEventJob_back {

    @Autowired
    private MonitorMapper monitorMapper;

    @Value("${event.time}")
    private String time;

//    @Scheduled(fixedRateString = "${event.checkTime}")
    public void updateEvent() {
        // 将数据接收处的map复制
        ConcurrentMap<String, JSONObject> cpMap = carLicense;
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取当前时间前120分钟的时间
        LocalDateTime thirtyMinutesBefore = now.minusMinutes(120);
        // 创建格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间和当前时间前30分钟的时间
        String now_time = now.format(formatter);
        String format_time = thirtyMinutesBefore.format(formatter);
        // 查询近2个小时的数据
        List<VehicleRsuInfo> vehicleRsuInfos = monitorMapper.selectVehicleInfoByTime(now_time, format_time);
        HashMap<String, VehicleRsuInfo> startHashMap = new HashMap<>();
        HashMap<String, VehicleRsuInfo> endHashMap = new HashMap<>();
        if (!vehicleRsuInfos.isEmpty()) {
            for (VehicleRsuInfo vehicleRsuInfo : vehicleRsuInfos) {
                String erId = vehicleRsuInfo.getErId();
                if ("S001933030055210010".equals(erId)) {
                    startHashMap.put(vehicleRsuInfo.getRecordId(), vehicleRsuInfo);
                } else if ("S001933030055210017".equals(erId)) {
                    endHashMap.put(vehicleRsuInfo.getRecordId(), vehicleRsuInfo);
                }
            }
        }
        for (Map.Entry<String, VehicleRsuInfo> entry : startHashMap.entrySet()) {
            String key = entry.getKey();
            VehicleRsuInfo vehicleRsuInfo = entry.getValue();
            String detectTime = vehicleRsuInfo.getDetectTime();
            if (endHashMap.containsKey(key)) {
                VehicleRsuInfo endVehicle = endHashMap.get(key);
                long diff_time = calculateMinutesDifference(detectTime, endVehicle.getDetectTime());
                if (diff_time > Integer.parseInt(time)) {
                    EventCar eventCar = new EventCar();
                    eventCar.setEventNumber(1);
                    eventCar.setRecordCarId(vehicleRsuInfo.getRecordId() + vehicleRsuInfo.getCar_Id() + "3");
                    eventCar.setRecordId(vehicleRsuInfo.getRecordId());
                    eventCar.setErId(vehicleRsuInfo.getErId());
                    eventCar.setEventType("3");
                    eventCar.setCarId(vehicleRsuInfo.getCar_Id());
                    eventCar.setTime(now_time);
                    eventCar.setUpBridgeTime(detectTime);
                    eventCar.setDownBridgeTime(endVehicle.getDetectTime());
                    eventCar.setDetectTime(vehicleRsuInfo.getDetectTime());
                    eventCar.setGantryTime(vehicleRsuInfo.getDetectTime());
                    eventCar.setPlate(vehicleRsuInfo.getLicenseCode());
                    eventCar.setSpeed(String.valueOf(vehicleRsuInfo.getVehicleSpeed()));
                    eventCar.setType(String.valueOf(vehicleRsuInfo.getIdentifyType()));
                    eventCar.setHeadPic(vehicleRsuInfo.getHeadImage());
                    eventCar.setSidePic(vehicleRsuInfo.getSideImage());
                    eventCar.setVideo(vehicleRsuInfo.getVideo());
                    // 首先查询数据库中 是否存在该数据
                    List<EventCar> eventCars = monitorMapper.selectEventInfoByCarId(vehicleRsuInfo.getCar_Id());
                    if (eventCars.isEmpty()) {
                        monitorMapper.insertEvent(eventCar);
                    }
                }
            } else {
                long diff_time = calculateMinutesDifference(now_time, detectTime);
                if (diff_time > Integer.parseInt(time)) {
                    EventCar eventCar = new EventCar();
                    eventCar.setEventNumber(1);
                    eventCar.setRecordCarId(vehicleRsuInfo.getRecordId() + vehicleRsuInfo.getCar_Id() + "3");
                    eventCar.setRecordId(vehicleRsuInfo.getRecordId());
                    eventCar.setErId(vehicleRsuInfo.getErId());
                    eventCar.setEventType("3");
                    eventCar.setCarId(vehicleRsuInfo.getCar_Id());
                    eventCar.setTime(now_time);
                    eventCar.setDetectTime(vehicleRsuInfo.getDetectTime());
                    eventCar.setGantryTime(vehicleRsuInfo.getDetectTime());
                    eventCar.setPlate(vehicleRsuInfo.getLicenseCode());
                    eventCar.setUpBridgeTime(detectTime);
                    eventCar.setSpeed(String.valueOf(vehicleRsuInfo.getVehicleSpeed()));
                    eventCar.setType(String.valueOf(vehicleRsuInfo.getIdentifyType()));
                    eventCar.setHeadPic(vehicleRsuInfo.getHeadImage());
                    eventCar.setSidePic(vehicleRsuInfo.getSideImage());
                    eventCar.setVideo(vehicleRsuInfo.getVideo());
                    List<EventCar> eventCars = monitorMapper.selectEventInfoByCarId(vehicleRsuInfo.getCar_Id());
                    if (eventCars.isEmpty()) {
                        monitorMapper.insertEvent(eventCar);
                    }
                }
            }
        }
        ArrayList<String> inDownNotInList = endHashMap.keySet()
                .stream()
                .filter(key -> !startHashMap.containsKey(key))
                .collect(Collectors.toCollection(ArrayList::new));
        for (String s : inDownNotInList) {
            VehicleRsuInfo vehicleRsuInfo = endHashMap.get(s);
            String carId = vehicleRsuInfo.getCarId();
            String detectTime = vehicleRsuInfo.getDetectTime();
            List<EventCar> eventCars = monitorMapper.selectEventInfoByCarIdAndEventType(carId,"3");
            eventCars.forEach(eventCar -> {
                if (StringUtils.isEmpty(eventCar.getDownBridgeTime())) {
                    eventCar.setDownBridgeTime(detectTime);
                }
                log.info("仅存在上桥数据,同时满足事件类型是滞留事件的数据");
                monitorMapper.insertEvent(eventCar);
            });
        }
    }

}
